#include "Sock.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " port" << std::endl;
}

void *Handler(void *arg)
{

    pthread_detach(pthread_self());

    int sockfd = *(int *)arg;
    int opt = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    char buffer[1024];
    ssize_t size = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if (size > 0)
    {
        buffer[size] = 0;
        // std::cout << pthread_self() << ": " << buffer << std::endl;
        std::cout << buffer;

        std::string http_response = "http/1.0 200 Ok\n";
        // text/plain，正文是普通文本
        http_response += "Content-Type: text/plain\n";
        http_response += "\n";
        http_response += buffer;
        send(sockfd, http_response.c_str(), http_response.size(), 0);
    }
    close(sockfd);
    std::cout << "Service done" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    int listen_sockfd = Sock::Socket();
    Sock::Bind(listen_sockfd, atoi(argv[1]));
    Sock::Listen(listen_sockfd);
    while (true)
    {
        int sockfd = Sock::Accept(listen_sockfd);
        pthread_t tid;
        pthread_create(&tid, nullptr, Handler, (void *)&sockfd);
    }

    close(listen_sockfd);
    return 0;
}
